package util

import (
	"fmt"
	"os"
	"time"
)

func LogInfo(content string) {
	LogSave("", content, "info")
}
func LogError(content string) {
	LogSave("", content, "error")
}

// LogSave 写入日志文件
func LogSave(filename string, content string, logType string) bool {
	curTime := time.Now()
	LogPath := fmt.Sprintf("log/%04d/%02d/", curTime.Year(), curTime.Month())
	logFileName := fmt.Sprintf("%04d%02d%02d%s.log", curTime.Year(), curTime.Month(), curTime.Day(), filename)
	err := os.MkdirAll(LogPath, 777)
	if err != nil {
		return false
	}
	_, err = os.Stat(LogPath + logFileName)
	if err != nil {
		if !os.IsExist(err) {
			_, err := os.Create(LogPath + logFileName)
			if err != nil {
				return false
			}
		}
	}
	file, err := os.OpenFile(LogPath+logFileName, os.O_APPEND|os.O_WRONLY, os.ModeAppend)
	defer func(file *os.File) {
		err := file.Close()
		if err != nil {

		}
	}(file)
	if err != nil {
		return false
	}
	logContent := fmt.Sprintf("%04d-%02d-%02d %02d:%02d:%02d [%s] %s %s", curTime.Year(), curTime.Month(), curTime.Day(), curTime.Hour(), curTime.Minute(), curTime.Second(), logType, GetLocalIP(), content)
	_, err = file.WriteString(logContent + "\n")
	if err != nil {
		return false
	}
	return true
}
